package com.people.core.validator.valid;

import com.people.core.validator.annotation.CompareValid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * 状态值验证器
 *
 * @author yuanqinglong
 * @date 2022/3/25 17:54
 */
public class CompareValidator implements ConstraintValidator<CompareValid, Number> {

    private CompareValid.Compare compare = null;

    private Long value;

    @Override
    public void initialize(CompareValid constraintAnnotation) {
        synchronized (CompareValid.class) {
            compare = constraintAnnotation.compare();
            value = constraintAnnotation.value();
        }
    }

    @Override
    public boolean isValid(Number number, ConstraintValidatorContext context) {
        if (number == null) {
            return true;
        }
        switch (compare) {
            case GTE:
                return number.longValue() >= value;
            case GT:
                return number.longValue() > value;
            case LTE:
                return number.longValue() <= value;
            case LT:
                return number.longValue() < value;
            case EQ:
            default:
                return Objects.equals(number.longValue(), value);
        }
    }
}
